<template>
  <div> authredirect
    {{test}}
    <div>{{user.name}}</div>
    <img :src="user.avatar" alt="logon">
    <div>{{user.email}}</div>
    <div>{{user.extattr.attrs[0].name}}</div>
    <div>{{user.extattr.attrs[0].value}}</div>
  </div>
</template>
<script>
  import Cookies from "js-cookie";
  import { fetchUser } from "@/api/user";
  export default {
    name: "authredirect",
    data() {
      return {
        test: "OK",
        user: {}
      };
    },
    methods: {
      getParam(hash, paramName) {
        let paramValue = "";
        let isFound = !1;
        if (hash.indexOf("?") <= 0 && hash.indexOf("=") > 1) {
          var arrSource = unescape(hash)
            .substring(0, hash.length)
            .split("&");
          let i = 0;
          while (
            i < arrSource.length &&
            !isFound &&
            arrSource[i].indexOf("=") > 0 &&
            arrSource[i].split("=")[0].toLowerCase() === paramName.toLowerCase()
          ) {
            paramValue = arrSource[i].split("=")[1];
            isFound = !0;
            i++;
          }
        }
        return paramValue;
      },
      getUser() {
        fetchUser()
          .then(res => {
            console.log("res", res);
            this.user = res.data;
            // console.log('this.user',this.user);

            setTimeout(function() {
              window.close();
            }, 5000);
          })
          .catch(err => {
            console.log(err);
            setTimeout(function() {
              window.close();
            }, 5000);
          });
      }
    },
    created() {
      let code = this.getParam(
        window.location.hash.slice(window.location.hash.indexOf("?") + 1),
        "code"
      );
      Cookies.set("code", code);

      this.getUser();

      if (window.opener) {
        window.opener.location.href =
          window.location.origin +
          "/#/login?" +
          window.location.hash.slice(window.location.hash.indexOf("?") + 1);
      } else {
        console.log("window.opener not found");
      }
    }
  };
</script>
